package longcaisuyun.longcai.com.yiliubabalongcaisuyun;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zcx.helper.secret.SecretAESDESede;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import longcaisuyun.longcai.com.mystatic.publicUrl;
import longcaisuyun.longcai.com.utils.Tools;
import longcaisuyun.longcai.com.view.ChangeAddressDialog;
import wh.utils.StringUtils;


//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//         佛祖保佑             永无BUG
//         佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//                  别人笑我忒疯癫，我笑自己命太贱；
//                  不见满街漂亮妹，哪个归得程序员？
/************************************************************/
//
/************************************************************/

/**
 * 加盟资料页面
 */
public class JiaMengziliaoActivity extends Activity implements View.OnClickListener {
    TextView t_chexing, tv_city;
    EditText et_name, et_num, et_phone, et_carnum;
    Button bt_next;
    String s = "";
    String id = "";
    String carid = "";
    String mobile = "";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jia_mengziliao);
        MyApplication.getInstance().addActivity(this);
        View view = getWindow().getDecorView();
        MyApplication.ScaleScreenHelper.loadView((ViewGroup) view);
        Intent intent = getIntent();
        mobile = intent.getStringExtra("mobile");
        ViewInit();
    }

    private void ViewInit() {
        LinearLayout fanhui_lin = (LinearLayout) findViewById(R.id.fanhui_lin);
        fanhui_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        t_chexing = (TextView) findViewById(R.id.t_chexing);
        t_chexing.setOnClickListener(this);
        bt_next = (Button) findViewById(R.id.bt_next);
        bt_next.setOnClickListener(this);
        et_name = (EditText) findViewById(R.id.et_name);
        et_num = (EditText) findViewById(R.id.et_num);
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_city.setOnClickListener(this);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_carnum = (EditText) findViewById(R.id.et_carnum);
        et_name.setSelection(et_name.length());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.t_chexing:
                if (!id.equals("")) {
                    httpPost();
                } else {
                    Toast.makeText(JiaMengziliaoActivity.this, "请先选择城市信息", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.bt_next:
                switch (isok()) {
                    case 1:
                        Intent intent_photo = new Intent();
                        intent_photo.setClass(JiaMengziliaoActivity.this, JiaMengPhotoActivity.class);
                        //姓名
                        intent_photo.putExtra("username", et_name.getText().toString());
                        //身份证
                        intent_photo.putExtra("cardnumber", et_num.getText().toString());
                        //城市id
                        intent_photo.putExtra("cityid", id);
                        //邀请人手机号码
                        intent_photo.putExtra("mobile2", et_phone.getText().toString());
                        //车型id
                        intent_photo.putExtra("cid", carid);
                        //车牌号
                        intent_photo.putExtra("license", et_carnum.getText().toString());
                        //电话号
                        intent_photo.putExtra("mobile", mobile);
                        startActivity(intent_photo.setClass(JiaMengziliaoActivity.this, JiaMengPhotoActivity.class));
                        break;
                    case 0:
                        Toast.makeText(JiaMengziliaoActivity.this, "您还没有输入姓名", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(JiaMengziliaoActivity.this, "邀请人手机号码格式错误，请检查后重新填写", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(JiaMengziliaoActivity.this, "身份证格式错误，请检查后重新填写", Toast.LENGTH_SHORT).show();
                        break;
                    case 4:
                        Toast.makeText(JiaMengziliaoActivity.this, "车牌号填写错误,请重新填写", Toast.LENGTH_SHORT).show();
                        break;
                    case 5:
                        Toast.makeText(JiaMengziliaoActivity.this, "您还没有输入身份证号", Toast.LENGTH_SHORT).show();
                        break;
                    case 6:
                        Toast.makeText(JiaMengziliaoActivity.this, "您还没有选择接单城市", Toast.LENGTH_SHORT).show();
                        break;
                    case 7:
                        Toast.makeText(JiaMengziliaoActivity.this, "您还没有选择车型", Toast.LENGTH_SHORT).show();
                        break;
                    case 8:
                        Toast.makeText(JiaMengziliaoActivity.this, "您还没有输入车牌号", Toast.LENGTH_SHORT).show();
                        break;

                }
                Log.e("kEYS", "" + et_name.getText().toString() + "-" + et_num.getText().toString() + "-" + id + "-" + et_phone.getText().toString() + "-" + carid + "-" + et_carnum.getText().toString() + "-" + mobile);
                break;
            case R.id.et_name:


                break;

            case R.id.tv_city:
                Intent intent = new Intent(JiaMengziliaoActivity.this, CityAcitvity.class);
                startActivityForResult(intent, 0);
                break;
        }
    }

    public int isok() {
        String reg = "^[\\u4e00-\\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(et_carnum.getText().toString());
        boolean b = matcher.matches();

        if (StringUtils.isEmpty(et_name.getText().toString())){
            return 0;
        }else if (StringUtils.isEmpty(et_num.getText().toString())){
            return 5;
        } else if (!Tools.personIdValidation(et_num.getText().toString())) {
            return 3;
        } else if (StringUtils.isEmpty(id)){
            return 6;
        }else if (!StringUtils.isPhone(et_phone.getText().toString())&&!StringUtils.isEmpty(et_phone.getText().toString())){
            return 2;
        }else if (StringUtils.isEmpty(carid)){
            return 7;
        }else if (StringUtils.isEmpty(et_carnum.getText().toString())){
            return 8;
        } else if (!b||et_carnum.getText().toString().length()!=7) {
            return 4;
        }
        return 1;
    }


    private void httpPost() {
        final SecretAESDESede secretAESDESede = new SecretAESDESede("123456781234567812345678", "12345678", SecretAESDESede.DESEDE_CBC_PKCS5PADDING);
        final FinalHttp finalHttp = new FinalHttp();
        AjaxParams params = new AjaxParams();

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("areaid", id);

            try {
                params.put("Keys", secretAESDESede.encrypt(jsonObject.toString()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        finalHttp.post(publicUrl.car, params, new AjaxCallBack<String>() {


            public void onStart() {
                super.onStart();
                MyApplication.myviewutil.startProgressDialog(JiaMengziliaoActivity.this, finalHttp, publicUrl.car);
            }

            public void onSuccess(String s) {
                super.onSuccess(s);

                try {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(secretAESDESede.decrypt(s));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String Message = jsonObject.getString("message");
                    if (Message.equals("1")) {
                        JSONArray jsonArray = jsonObject.getJSONArray("list");
                        MyApplication.myviewutil.stopProgressDialog();
                        if (jsonArray.length() > 0) {
                            diag(jsonArray);
                        } else {
                            Toast.makeText(JiaMengziliaoActivity.this, "该城市暂无可选车型", Toast.LENGTH_SHORT).show();

                        }

                    } else {
                        Toast.makeText(JiaMengziliaoActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                MyApplication.myviewutil.stopProgressDialog();
            }

            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                MyApplication.myviewutil.stopProgressDialog();
            }
        });
    }

    public void diag(JSONArray jsonArray) {
        //车型
        final ArrayList<String> list = new ArrayList<String>();
        //类型
        Map<String, String[]> m = new HashMap<String, String[]>();
        //车的id
        final ArrayList<String> list_id = new ArrayList<String>();

        for (int j = 0; j < jsonArray.length(); j++) {
            try {
                JSONObject jsonObject = (JSONObject) jsonArray.get(j);
                list.add(jsonObject.getString("model"));
                String[] s = {jsonObject.getString("long") + "x" + jsonObject.getString("wide") + "x" + jsonObject.getString("high")};
                m.put(jsonObject.getString("model"), s);
                list_id.add(jsonObject.getString("id"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        ChangeAddressDialog mChangeAddressDialog = new ChangeAddressDialog(
                JiaMengziliaoActivity.this, list, m);
        Window window = mChangeAddressDialog.getWindow();
        window.setWindowAnimations(R.style.mypopwindow_anim_style);
        window.setGravity(Gravity.BOTTOM);
        mChangeAddressDialog.setAddress("面包车1", "0");
        mChangeAddressDialog.show();
        mChangeAddressDialog
                .setAddresskListener(new ChangeAddressDialog.OnAddressCListener() {
                    public void onClick(String province, String city) {
                        // TODO Auto-generated method stub
                        carid = list_id.get(list.indexOf(province));
                       /* Toast.makeText(JiaMengziliaoActivity.this,
                                province + "-" + city + "-" + carid,
                                Toast.LENGTH_SHORT).show();*/
                        t_chexing.setTextColor(Color.parseColor("#5f5f5f"));
                        t_chexing.setText(province + "型号" + "---" + city + "米");
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0 && resultCode == 1) {
            id = data.getStringExtra("id");
            MyApplication.myPreferences.saveCity(id);
            tv_city.setText(data.getStringExtra("content"));
        }
    }
}
